﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		AsyncBaseService.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            AsyncBaseService.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Threading;
using Dexter.Async.Executor;

namespace Dexter.Async.Services {

	public class AsyncService : IAsyncService {
		public  AsyncService ( IAsyncExecutor asyncExecutor ) {
			AsyncExecutor = asyncExecutor;
		}

		IAsyncExecutor AsyncExecutor { get; set; }

		/// <summary>
		/// Calls a function asyncronously.
		/// </summary>
		/// <param name="call">The call.</param>
		/// <param name="state">The state.</param>
		/// <returns></returns>
		public virtual VoidAsyncResult AsyncCall ( Action <Object> call , Object state ) {
			var result = new VoidAsyncResult ( null , null );

			if ( ExecutionContext.IsFlowSuppressed ( ) ) {
				ExecutionContext.RestoreFlow ( );
			}

			ThreadPool.QueueUserWorkItem ( CallWrapper , new InvocationToken ( call , state , result ) );
			return result;
		}

		/// <summary>
		/// This is the real function called, here we can do some management. This function is called 
		/// in another thread, so we need to manage the lifecycle of the session in this point to avoid
		/// having unclosed sessions.
		/// </summary>
		/// <param name="state">The state.</param>
		void CallWrapper ( Object state ) {
			AsyncExecutor.Execute ( ( InvocationToken ) state );
		}
	}
}
